package net.lcqf.udp.send.message;

import cn.hutool.json.JSONUtil;
import net.lcqf.udp.game.RoomManager;
import net.lcqf.udp.kcp.Ukcp;
import net.lcqf.udp.request.RoomRequest;
import net.lcqf.udp.response.RoomResponse;
import net.lcqf.udp.send.MessageBaseService;
import net.lcqf.udp.send.MessageFactory;
import net.lcqf.udp.send.RequestType;
import net.lcqf.udp.server.MsgInfo;
import net.lcqf.udp.utils.LocalCacheUtil;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;

/**
 * +----------------------------------------------------------------------
 * // | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * // +----------------------------------------------------------------------
 * // | Copyright (c) 2021-2025 聊来 All rights reserved.
 * // +----------------------------------------------------------------------
 * // | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * // +----------------------------------------------------------------------
 * // | @Author: 聊来 <18970881148@qq.com>
 * // +----------------------------------------------------------------------
 * // | DateTime: 2025/3/20 10:51
 * // +----------------------------------------------------------------------
 */

@Service
public class Room implements MessageBaseService {

    @Override
    @PostConstruct
    public void init() {
        MessageFactory.register(RequestType.JOIN_ROOM.getCustomOrdinal(), this);
    }

    @Override
    public Object sendMessage(Ukcp kcp, MsgInfo msgInfo) {
        RoomRequest request = JSONUtil.toBean(msgInfo.getData(), RoomRequest.class);


        RoomManager tClass = LocalCacheUtil.JOIN_ROOM.computeIfAbsent(request.getRoomId(), k -> new RoomManager(request.getRoomId(), new ArrayList<>(), new ArrayList<>()));
        tClass.addChannel(msgInfo.getChannelId());

        RoomResponse room = new RoomResponse();
        room.setRoomId(request.getRoomId());
        room.setChannelId(msgInfo.getChannelId());
        room.setKcp(kcp);

        return room;
    }
}
